﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Threading;

namespace Mvvm.Common.WindowExtensions
{
    public static class TopMostExtensions
    {
        /// <summary>
        /// 设置窗体置顶
        /// <para>默认是一直置顶，如果不需要一直置顶功能，请设置option的IsAlways参数为false</para>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="optionAction"></param>
        /// <returns></returns>
        public static T SetTopMost<T>(this T t, Action<TopMostOption> optionAction = null) where T : Window
        {
            t.Topmost = true;
            TopMostOption option = new TopMostOption();
            optionAction?.Invoke(option);
            if (option.IsAlways == false)
            {
                return t;
            }

            if (t.IsLoaded)
            {
                SetWindowTopMost(t, option);
            }
            else
            {
                t.Loaded += (sender, args) => { SetWindowTopMost(t, option); };
            }

            return t;
        }

        private static void SetWindowTopMost(Window window, TopMostOption option)
        {
            if (option.IsCancel) return;
            bool isClose = false;
            window.Closed += (sender, args) => isClose = true;
            DispatcherTimer timer = new DispatcherTimer();
            timer.Tick += (sender, args) =>
            {
                if (isClose || option.IsCancel)
                {
                    timer.Stop();
                    return;
                }

                if (window.WindowState == WindowState.Minimized)
                {
                    return;
                }

                window.Topmost = false;
                window.Topmost = true;
            };
            timer.Interval = option.CheckTopInterval;
            timer.Start();
        }
    }
}
